package www.openteam.com.workorder;


import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.percent.PercentRelativeLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.OTApplication;
import www.openteam.com.R;
import www.openteam.com.base.OtherBaseFragment;
import www.openteam.com.bean.GroupCount;
import www.openteam.com.bean.Inputer;
import www.openteam.com.bean.JiJian;
import www.openteam.com.bean.MachineInfo;
import www.openteam.com.bean.PDistrubiton_JijianNumb;
import www.openteam.com.bean.PeopleGroup;
import www.openteam.com.bean.UpdateInfo;
import www.openteam.com.bean.WorkOrder;
import www.openteam.com.tool.EditTextShakeTool;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.business.ScanActivity;
import www.openteam.com.ui.business.other.HZRBPSearchFragment;
import www.openteam.com.ui.business.other.WOSearchFragment;
import www.openteam.com.widget.ItemRemoveRecycleView;

/**
 * 杭州日报的数据采集
 */

public class HZRB_WorkOrderFragment extends OtherBaseFragment<HZRB_WorkOrderPresenter> implements
        HZRB_WorkOrderContract.WorkOrderView {


    private static final String TAG = HZRB_WorkOrderFragment.class.getSimpleName();
    @Bind(R.id.et_inputer)
    EditText et_inputer;
    @Bind(R.id.et_work_order_id)
    EditText et_work_order_id;
    @Bind(R.id.et_s_time)
    EditText et_s_time;
    @Bind(R.id.et_machine_id)
    EditText et_machine_id;
    @Bind(R.id.et_e_time)
    EditText et_e_time;
    @Bind(R.id.et_order_id)
    EditText et_order_id;
    @Bind(R.id.et_cust_name)
    EditText et_cust_name;
    @Bind(R.id.et_partId)
    EditText et_partId;
    @Bind(R.id.et_procedure)
    EditText et_procedure;
    @Bind(R.id.et_product_name)
    EditText et_product_name;
    @Bind(R.id.et_should_num)
    EditText et_should_num;
    @Bind(R.id.et_already_num)
    EditText et_already_num;
    @Bind(R.id.et_produce_num)
    EditText et_produce_num;
    @Bind(R.id.et_no_finish_num)
    EditText et_no_finish_num;
    @Bind(R.id.et_team_group)
    EditText et_team_group;
    @Bind(R.id.et_people_group)
    EditText et_people_group;
    //    @Bind(R.id.btn_add)
//    Button btn_add;
    @Bind(R.id.btn_cancel)
    Button btn_cancel;
    @Bind(R.id.btn_keep)
    Button btn_keep;
    //    @Bind(R.id.btn_delete)
//    Button btn_delete;
    @Bind(R.id.bt_w_delete)
    Button bt_w_delete;
    @Bind(R.id.btn_inpter)
    Button btn_inpter;
    @Bind(R.id.iv_scan)
    ImageView iv_scan;
    @Bind(R.id.iv_scan_jt)
    ImageView iv_scan_jt;
    @Bind(R.id.cb_is_finish)
    CheckBox cb_is_finish;
    @Bind(R.id.sp_print_type)
    AppCompatSpinner spPrintType;
    @Bind(R.id.sp_print_PoNe)
    AppCompatSpinner spPrintPoNe;
    @Bind(R.id.et_print_color)
    EditText etPrintColor;
    @Bind(R.id.et_print_code)
    EditText etPrintCode;
    @Bind(R.id.et_print_prctType)
    EditText etPrintPrctType;
    @Bind(R.id.et_draftflowD)
    EditText etDraftflowD;
    @Bind(R.id.et_halfStorage)
    EditText etHalfStorage;
    @Bind(R.id.et_changeTime)
    EditText etChangeTime;
    @Bind(R.id.et_waitTime)
    EditText etWaitTime;
    @Bind(R.id.et_delayTime)
    EditText etDelayTime;
    //    @Bind(R.id.add_item)
//    ImageButton add_item;
    @Bind(R.id.rl_9)
    PercentRelativeLayout rl9;
    @Bind(R.id.rl_10)
    PercentRelativeLayout rl10;
    @Bind(R.id.rl_11)
    PercentRelativeLayout rl11;
    @Bind(R.id.rl_12)
    PercentRelativeLayout rl12;
    @Bind(R.id.rl_13)
    PercentRelativeLayout rl13;
    @Bind(R.id.tv_remark)
    TextView tvRemark;
    @Bind(R.id.et_remark)
    EditText etRemark;

    private Intent intent;
    int RESULT_WO_ID = 1111;
    int RESULT_WO_MID = 1112;
    EditTextShakeTool editTextShakeTool;
    private double alreadyNum;
    private double nofinishNum;
    private double thisAllow;
    private String procno = "";
    SharedPreferences workSP = OTApplication.getmContext().getSharedPreferences("wk",
            getContext().MODE_PRIVATE);
    public Resources resources;
    private boolean isFinal = false;
    private ItemRemoveRecycleView itemRemoveRecycleView;
    private ArrayList<GroupCount> groupCount;
    private int sheetNumb;
    List<WorkOrder.DataEntity> realHandleWorkOrder;
    private String machine_id;
    private String work_id;
    private String machine_code= "";

    private ImageButton add_item;
    private int count = 0;
    private FragmentManager manager;
    private FragmentTransaction ft;
    private WOSearchFragment woSearchFragment;
    private HZRBPSearchFragment hzrbpSearchFragment;
    private Bundle args;
    private HZRBWorkAdapter adapter;
    private boolean isExist = false;
    private boolean isFinish = false;
    private String inpuer;
    private int barZbid;
    private boolean isInputer = false;
    private boolean isWorkId = false;
    private boolean isMachineInfo = false;
    private int id;
    private LinearLayoutManager linearLayoutManager;
    private ArrayAdapter<String> printTypeAdapter;
    private ArrayAdapter<String> printPoNeAdapter;
    private ArrayAdapter<String> emptyAdapter;
    private ArrayList<PDistrubiton_JijianNumb.DataBeanX.DataBean> pdistrubition;
    private String mId;


    @Override
    protected void initData() {
//        Log.e(TAG, "initData: "+"HZRB_WorkOrderFragment" );
        resources = getResources();
        ArrayList<String> printTypeList = new ArrayList<>();
        printTypeList.add("正翻");
        printTypeList.add("自翻");
        printTypeList.add("滚翻");
        printTypeList.add("双面");
        printTypeAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, printTypeList);
        printTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ArrayList<String> printPoNeList = new ArrayList<>();
        printPoNeList.add("正面");
        printPoNeList.add("反面");
        printPoNeAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, printPoNeList);
        printPoNeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        emptyAdapter = new ArrayAdapter<String>
                (getContext(), android.R.layout.simple_spinner_item);
//        mProgressDialog = new ProgressDialog(getContext());
        et_inputer.setText(mySetting.getString("mCode", ""));
    }


    @Override
    protected void initListener() {
//        btn_add.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
//        btn_delete.setOnClickListener(this);
        bt_w_delete.setOnClickListener(this);
        btn_keep.setOnClickListener(this);
        iv_scan.setOnClickListener(this);
        btn_inpter.setOnClickListener(this);
        iv_scan_jt.setOnClickListener(this);
        add_item.setOnClickListener(this);
        et_people_group.setOnClickListener(this);
        /**
         * 20170518 去掉班组
         */
        et_team_group.setOnClickListener(this);
        et_produce_num.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                int tJudge = 0;
                tJudge = realHandleWorkOrder.get(0).getIsPrint() == 1 ? 1 : 3;  // ?a:b
                tJudge += realHandleWorkOrder.get(0).getIsTake() == 1 ? 8 : 2;   //?c:d
                // 只是打印不领料 a+d 3,  只是领料不打印 b+c 11 ,
                // 又是打印,又领料 a+c,9  既不是打印也不领料 b+d; 5
                double max;
                double inp;
                double min;
                switch (tJudge) {
                    case 3:
                        max = realHandleWorkOrder.get(0).getAddPaper() + nofinishNum;
                        inp = Double.parseDouble(et_produce_num.getText().toString());
                        et_produce_num.setText(getMin(max, inp) + "");
                        Log.d(TAG, "onEditorAction: " + (thisAllow - getMin(max, inp)));
                        et_no_finish_num.setText(thisAllow - getMin(max, inp) + "");
                        break;
                    case 5:
                        inp = Double.parseDouble(et_produce_num.getText().toString());
                        et_produce_num.setText(getMin(nofinishNum, inp) + "");
                        et_no_finish_num.setText(thisAllow - getMin(nofinishNum, inp) + "");
                        Log.d(TAG, "onEditorAction: " + (thisAllow - getMin(nofinishNum, inp)));
                        break;
                    case 9:
                        if (sheetNumb > 0) {
                            max = realHandleWorkOrder.get(0).getAddPaper() + nofinishNum;
                            inp = Double.parseDouble(et_produce_num.getText().toString());
                            min = getMin(max, sheetNumb);
                            et_produce_num.setText(getMin(min, inp) + "");
                            et_no_finish_num.setText(thisAllow - getMin(min, inp) + "");
                            Log.d(TAG, "onEditorAction: " + (thisAllow - thisAllow - getMin(min, inp)));
                        } else {
                            ToastUtil.showToast(getContext(), resources.getString(R.string.takeMetral_hint));
                            et_produce_num.setText(0 + "");
                            et_no_finish_num.setText(thisAllow - 0 + "");
                            Log.d(TAG, "onEditorAction: " + (thisAllow - 0));
                        }
                        break;
                    case 11:
                        if (sheetNumb > 0) {
                            inp = Double.parseDouble(et_produce_num.getText().toString());
                            min = getMin(nofinishNum, sheetNumb);
                            et_produce_num.setText(getMin(min, inp) + "");
                            et_no_finish_num.setText(thisAllow - getMin(min, inp) + "");
                            Log.d(TAG, "onEditorAction: " + (thisAllow - getMin(min, inp)));
                        } else {
                            ToastUtil.showToast(getContext(), resources.getString(R.string.takeMetral_hint));
                            et_produce_num.setText(0 + "");
                            et_no_finish_num.setText(thisAllow - 0 + "");
                            Log.d(TAG, "onEditorAction: " + (thisAllow - 0));
                        }
                        break;
                }


                return false;
            }
        });

        cb_is_finish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                isFinish = isChecked;
            }
        });
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this, view);
        manager = getFragmentManager();
        add_item = (ImageButton) view.findViewById(R.id.add_item);
        itemRemoveRecycleView = (ItemRemoveRecycleView) view.findViewById(R.id.rv_wor);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        itemRemoveRecycleView.setLayoutManager(linearLayoutManager);
    }


    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected HZRB_WorkOrderPresenter loadPresenter() {
        return new HZRB_WorkOrderPresenter();
    }

    @Override
    public void onRefresh() {

    }


    private double getMin(double a, double b) {

        double min = a;
        if (a > b) {

            min = b;

        }

        return min;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        String work_order_id = data.getStringExtra("work_order_id");
        String inputer = workSP.getString("inputer", "");
        if (inputer.isEmpty()) {
            ToastUtil.showToast(getContext(), "请确认录入员");
        } else {
            if (requestCode == RESULT_WO_ID && !work_order_id.equals("")) {
                mProgressDialog.show();
                workSP.edit().putString("work_id", work_order_id).commit();
                mPresenter.queryWO(work_order_id, getStype(), getMoreCom(),
                        mySetting.getInt(mId, 0));
            } else if (requestCode == RESULT_WO_MID && !work_order_id.equals("")) {
                mProgressDialog.show();
//            workSP.edit().putString("procno", procno).commit();
//            machine_id = work_order_id + "-" + procno;
                machine_id = work_order_id;
                machine_code = machine_id;
                mPresenter.findMachine(machine_id,
                        inputer, workSP.getString("procno", ""),
                        et_work_order_id.getText().toString(), getStype(), getMoreCom());
            }
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_work_order_hzrb;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.btn_add:
//                ToastUtil.showToast(OTApplication.getContext(), "add");
//                break;
            case R.id.btn_keep:
                keepTheData(isExist);
                break;
            case R.id.btn_cancel:
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
                alertDialog.setTitle(resources.getString(R.string.work_order_cancel));
                alertDialog.setMessage(resources.getString(R.string.message_empty));
                alertDialog.setPositiveButton(resources.getText(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        emptyEt();
                    }
                });
                alertDialog.setNegativeButton(resources.getText(R.string.cancel), null);
                alertDialog.show();
                break;
//            case R.id.btn_delete:
//                ToastUtil.showToast(OTApplication.getContext(), "btn_delete");
//                break;
            //班组人组联合搜索
            case R.id.bt_w_delete:
                if (et_inputer.getText().toString().equals("") &&
                        !isInputer) {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_inputer_hint));
                    new EditTextShakeTool(getActivity()).shake(et_inputer);
                    et_inputer.setFocusable(true);
                } else if (et_work_order_id.getText().toString().equals("") &&
                        !isWorkId) {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_id_hint));
                    new EditTextShakeTool(getActivity()).shake(et_work_order_id);
                    et_inputer.setFocusable(true);
                } else if (et_machine_id.getText().toString().equals("") &&
                        !isMachineInfo) {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_machine_hint));
                    new EditTextShakeTool(getActivity()).shake(et_machine_id);
                    et_inputer.setFocusable(true);
                } else if (!et_people_group.getText().toString().equals("")) {
                    mProgressDialog.show();

                    mPresenter.findWorkPrice(workSP.getString("machine_id", ""),
                            et_team_group.getText().toString(),
                            et_people_group.getText().toString(), getStype(), getMoreCom());
                } else {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.peoplenotnull));
                }
                break;
            case R.id.iv_scan:
                iv_scan.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                if (et_inputer.getText().toString().equals("") &&
                        !isInputer) {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_inputer_hint));
                    new EditTextShakeTool(getActivity()).shake(et_inputer);
                    et_inputer.setFocusable(true);
                } else {
                    if (et_work_order_id.getText().toString().equals("")) {
                        intent = new Intent(getActivity(), ScanActivity.class);
                        startActivityForResult(intent, RESULT_WO_ID);
                    } else if (!et_work_order_id.getText().toString().equals("")
                            && !isWorkId) {
                        mProgressDialog.show();
                        work_id = et_work_order_id.getText().toString();
                        mPresenter.queryWO(et_work_order_id.getText().toString(), getStype(), getMoreCom(),
                                mySetting.getInt("mId", 0));
                    } else {
                        ToastUtil.showToast(getContext(), resources.getString(R.string.cancel_hint));
                    }
                }

                break;
            case R.id.iv_scan_jt:
//                Log.d(TAG, "onClick: " + workSP.getString("machine_id", "").equals("") + ":" +
//                        !et_machine_id.getText().toString().equals(""));
                String searchInputer = workSP.getString("inputer", "");

                if (searchInputer.equals("") && isInputer) {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_inputer_hint));
                    new EditTextShakeTool(getActivity()).shake(et_inputer);
                    et_inputer.setFocusable(true);
                } else if (et_work_order_id.getText().toString().equals("") &&
                        !isWorkId) {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.wo_id_hint));
                    new EditTextShakeTool(getActivity()).shake(et_work_order_id);
                    et_inputer.setFocusable(true);
                } else {
                    if (et_machine_id.getText().toString().equals("")) {
                        intent = new Intent(getActivity(), ScanActivity.class);
                        startActivityForResult(intent, RESULT_WO_MID);
                    } else if (!et_machine_id.getText().toString().equals("")
                            && !isMachineInfo) {
                        mProgressDialog.show();
                        //machine_id = et_machine_id.getText().toString() + "-" + procno;

                        machine_id = et_machine_id.getText().toString();
                        machine_code = et_machine_id.getText().toString();
                        mPresenter.findMachine(machine_id,
                                searchInputer,
                                workSP.getString("procno", ""),
                                et_work_order_id.getText().toString(), getStype(), getMoreCom());
                    } else {
                        ToastUtil.showToast(getContext(), resources.getString(R.string.cancel_hint));
                    }
                }

                break;
            case R.id.btn_inpter:
                queryWO();
                break;
            case R.id.add_item:
                hzrbpSearchFragment = new HZRBPSearchFragment();
                Bundle arg = new Bundle();
                ft = manager.beginTransaction();
                ft.hide(this).add(R.id.fragment_container, hzrbpSearchFragment, "hzrbpSearchFragment");
                ft.addToBackStack(null);
                ft.commit();
                hzrbpSearchFragment.theOkClick(new HZRBPSearchFragment.ButtonOkClick() {
                    @Override
                    public void returnWorker(JiJian jiJian) {
                        PDistrubiton_JijianNumb.DataBeanX.DataBean dataEntity;
                        if (adapter == null) {
                            Log.d(TAG, "returnWorker:  null" + jiJian.getCode());
                            //如果adpter==null 。就要初始化apdater 和 pdistrubition
                            adapter = new HZRBWorkAdapter(getContext());
                            //计件数量点击事件
                            adapter.setOnJiJianNumbClickListener(new HZRBWorkAdapter.OnJiJianNumbClickListener() {
                                @Override
                                public void onClick(final int postion) {
                                    final EditText inputServer = new EditText(getContext());
                                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                                    builder.setTitle("计件数量").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer)
                                            .setNegativeButton("取消", null);
                                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

                                        public void onClick(DialogInterface dialog, int which) {
                                            pdistrubition.get(postion).setJijianNumb(stringToNumb(inputServer.getText().toString()));
                                            adapter.notifyDataSetChanged();

                                        }
                                    });
                                    builder.show();
                                }
                            });
                            adapter.addContext(getContext());
                            pdistrubition = new ArrayList<>();
                            dataEntity = new PDistrubiton_JijianNumb.DataBeanX.DataBean();
                            dataEntity.setId(1);
                            dataEntity.setCode(jiJian.getCode());
                            dataEntity.setJob(jiJian.getJob());
                            dataEntity.setName(jiJian.getName());

                            dataEntity.setJijianNumb(stringToNumb(jiJian.getSumnub()));//使用dutycode来存储计件数量，只是利用该类，并不代表真正的意思
                            pdistrubition.add(dataEntity);
                            adapter.addItems(pdistrubition);
                            itemRemoveRecycleView.setAdapter(adapter);
                            itemRemoveRecycleView.setOnItemClickListener(new ItemRemoveRecycleView.ItemOnListener() {
                                @Override
                                public void onItemDelete(int position) {

                                    adapter.removeItem(position);
                                    pdistrubition.remove(position);
                                    itemRemoveRecycleView.removeViewAt(position);

                                }
                            });
                        } else {
                            Log.d(TAG, "returnWorker:  not null" + jiJian.getCode());
                            dataEntity = new PDistrubiton_JijianNumb.DataBeanX.DataBean();
                            dataEntity.setId(pdistrubition.size());
                            dataEntity.setCode(jiJian.getCode());
                            dataEntity.setJob(jiJian.getJob());
                            dataEntity.setName(jiJian.getName());
                            dataEntity.setJijianNumb(stringToNumb(jiJian.getSumnub()));
                            boolean isE = false;
                            for (int i = 0; i < pdistrubition.size(); i++) {
                                if (jiJian.getCode().equals(pdistrubition.get(i).getCode())) {
                                    isE = true;
                                    break;
                                }
                            }
                            if (isE) {
                                ToastUtil.showToast(getContext(), "不能重复选择");
                            } else {
                                pdistrubition.add(dataEntity);
                                adapter.addItem(dataEntity);
                            }
                            itemRemoveRecycleView.setOnItemClickListener(new ItemRemoveRecycleView.ItemOnListener() {
                                @Override
                                public void onItemDelete(int position) {

                                    adapter.removeItem(position);
                                    pdistrubition.remove(position);
                                    itemRemoveRecycleView.removeViewAt(position);

                                }
                            });
                        }

                    }
                });
                break;
            case R.id.et_people_group:
                woSearchFragment = new WOSearchFragment();
                Bundle args = new Bundle();
                args.putInt("position", 1);
                args.putString("mark", "查询人组");
                woSearchFragment.setArguments(args);
                woSearchFragment.buttonSetOnclick(new WOSearchFragment.ButtonSelect() {
                    @Override
                    public void buttonOnclickSelect(PeopleGroup.DataEntity peopleGroup, int position) {
                        ft = manager.beginTransaction();
                        ft.remove(woSearchFragment).show(HZRB_WorkOrderFragment.this);
                        ft.addToBackStack(null);
                        ft.commit();
                        et_people_group.setText(peopleGroup.getGroupcount().toString());
                    }
                });
                args.putString("searchCondition", workSP.getString("machine_id", "").toString());
                ft = manager.beginTransaction();
                ft.hide(this).add(R.id.fragment_container, woSearchFragment, "woSearchFragment");
                ft.addToBackStack(null);
                ft.commit();

                break;
            /**
             * 20170518
             * 去掉班组查询
             */
            case R.id.et_team_group:
                woSearchFragment = new WOSearchFragment();
                args = new Bundle();
                args.putInt("position", 2);
                args.putString("mark", "查询班组");
                woSearchFragment.setArguments(args);
                woSearchFragment.buttonSetOnclick(new WOSearchFragment.ButtonSelect() {
                    @Override
                    public void buttonOnclickSelect(PeopleGroup.DataEntity peopleGroup, int position) {
                        ft = manager.beginTransaction();
                        ft.remove(woSearchFragment).show(HZRB_WorkOrderFragment.this);
                        ft.addToBackStack(null);
                        ft.commit();
                        et_team_group.setText(peopleGroup.getGroupcount().toString());
                    }
                });
                args.putString("searchCondition", workSP.getString("machine_id", "").toString());
                ft = manager.beginTransaction();

                ft.hide(this).add(R.id.fragment_container, woSearchFragment, "woSearchFragment");
                ft.addToBackStack(null);
                ft.commit();
                break;
            default:
                otherViewClick(view);
                break;
        }
//        if (null!=adapter){
//
//        }

    }

    private int stringToNumb(String sumnub) {
        return Integer.valueOf(sumnub.isEmpty() ? "0" : sumnub);
    }

    private Double stringToNumbD(String sumnub) {
        return Double.valueOf(null == sumnub || sumnub.equals(".0000") ? "0" : sumnub);
    }

    //存档时数据检查
    private void keepTheData(boolean isExist) {

        int userid = mySetting.getInt("mId", 0);//登录id
        String mName = mySetting.getString("mName", "");
        String procno = workSP.getString("procno", "");
        long sTime = workSP.getLong("sTime", 0L);
        String inpter = workSP.getString("inputer", "");//录入人员
        String machine_id = workSP.getString("machine_id", "");
        String inputerName = workSP.getString("inputerName", "");
        long eTime = workSP.getLong("eTime", 0L);
        WorkOrder.DataEntity rw = null;
        if (realHandleWorkOrder != null) {
            rw = realHandleWorkOrder.get(0);
        }

        Log.d(TAG, "keepTheData: " + userid + ":" + sTime + ":" + inpter + ":" + machine_id);
        if (isExist) {
            if (pdistrubition != null) {
                String produce_num = et_produce_num.getText().toString();
                if (!produce_num.equals("") && Double.parseDouble(produce_num) <= nofinishNum) {
                    groupCount = new ArrayList<>();
                    int num = 0;

                    for (int i = 0; i < pdistrubition.size(); i++) {

                        GroupCount gp = new GroupCount();
                        gp.setId(i);
                        gp.setZbid(barZbid + "");
                        gp.setEmployeeCode(pdistrubition.get(i).getCode());
                        gp.setDistributRate(stringToNumbD(pdistrubition.get(i).getDistributRate()));
                        gp.setJijianNumb(pdistrubition.get(i).getJijianNumb() + "");
                        gp.setProdNumb(Double.parseDouble(produce_num));
                        Log.d(TAG, "keepTheData: " + pdistrubition.get(i).getCode() + ":" + pdistrubition.get(i).getName());
                        groupCount.add(gp);
                    }
                    Gson gson = new Gson();
                    String str = gson.toJson(groupCount); //
//                String str = ""; //
                    try {
                        str = URLEncoder.encode(str, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    createProgressDialog(resources.getString(R.string.keeping));
//                    machine_code = "";
                    mPresenter.insertEProductionInfo(str, isFinish, rw.getRdsno(),
                            et_people_group.getText().toString(),
                            rw.getZbid(), eTime, eTime, rw.getPrdid() + "",
                            Double.parseDouble(produce_num),
                            machine_id, rw.getCode(), inpter, rw.getProcno(), rw.getCustid(), rw.getOrderno()
                            , Double.parseDouble(et_should_num.getText().toString())
                            , rw.getPartid(), mName, inputerName, userid, id, et_team_group.getText().toString(), getStype(), getMoreCom(),
                            spPrintType.getSelectedItem().toString(), spPrintPoNe.getSelectedItem().toString(),
                            getEditText(etPrintColor), getEditText(etPrintCode), getEditText(etPrintPrctType), getEditText(etDraftflowD), getEditText(etHalfStorage)
                            , getTextInt(etChangeTime), getTextInt(etWaitTime), getTextInt(etDelayTime),etRemark.getText().toString());


                } else {
                    ToastUtil.showToast(getContext(), resources.getString(R.string.producenum));
                }
            } else {
                ToastUtil.showToast(getContext(), resources.getString(R.string.countMan));
            }
        } else {
            if (null != rw && machine_id != "") {
                createProgressDialog(resources.getString(R.string.keeping));

                mPresenter.insertSProductionInfo(sTime,
                        rw.getZbid(), rw.getRdsno(), rw.getOrderno(), rw.getCustid(), sTime, rw.getPartid(),
                        rw.getPrdid() + "", Double.parseDouble(et_should_num.getText().toString()), rw.getCode(),
                        inpter, userid + "", machine_id, mName, inputerName, rw.getProcno(), getStype(), getMoreCom()
                );
            } else {
                ToastUtil.showToast(getContext(), resources.getString(R.string.wo_num_hint));
            }
        }

    }

    private String getEditText(EditText editText) {
        return editText.getText().toString();
    }

    private int getTextInt(EditText editText) {
        String text = editText.getText().toString();
        return Integer.valueOf(text.toString().isEmpty() ? "0" : text);
    }

    private void queryWO() {

        if (btn_inpter.getText().toString().equals(resources.getString(R.string.btn_ok_inputer))) {
            et_inputer.setFocusable(true);
            if (et_inputer.getText().toString().isEmpty()) {
                new EditTextShakeTool(getContext()).shake(et_inputer);
                et_inputer.setFocusable(true);
            } else {
                createProgressDialog(resources.getString(R.string.querying));
                inpuer = et_inputer.getText().toString();
                mPresenter.queryUserIsExist(et_inputer.getText().toString());
            }
        } else if (btn_inpter.getText().toString().equals(resources.getString(R.string.wo_mobify))) {
            emptyEt();
            et_inputer.setFocusable(true);
            et_inputer.setFocusableInTouchMode(true);
            btn_inpter.setText(resources.getString(R.string.btn_ok_inputer));
            et_inputer.setText("");
        }
    }

    @Override
    public String getName() {
        return null;
    }

    @Override
    public String getCode() {
        return null;
    }


    @Override
    public String getStype() {
        String stype = mySetting.getString("rCode", "");
        Log.d(TAG, "getStype: " + stype);
        return stype;
    }

    @Override
    public String getMoreCom() {
        String moreCom = mySetting.getString("rMoreCom", "");
//        Log.d(TAG, "getMoreCom: "+moreCom);
        return moreCom;
    }

    @Override
    public void queryISuccess(Inputer inputer) {
        mProgressDialog.cancel();
        et_inputer.setFocusable(false);
        et_inputer.setFocusableInTouchMode(false);
        workSP.edit().putString("inputer", inpuer).commit();
        workSP.edit().putString("inputerName", inputer.getData().get(0).getName()).commit();

//        Log.d(TAG, "queryISuccess: "+workSP.getString("inputer",""));
        isInputer = true;
        et_inputer.setText(et_inputer.getText().toString() + inputer.getData().get(0).getName());
        btn_inpter.setText(resources.getString(R.string.wo_mobify));
    }

    @Override
    public void queryIFail(String failMsg) {
//        if (mProgressDialog.isShowing()) {
        mProgressDialog.cancel();
//        }
        ToastUtil.showToast(getActivity(), failMsg);
        isInputer = false;
        new EditTextShakeTool(getActivity()).shake(et_inputer);
    }

    @Override
    public void queryWSuccess(WorkOrder workOrder) {
        mProgressDialog.cancel();
        et_work_order_id.setFocusableInTouchMode(false);
        et_work_order_id.setFocusable(false);
        workSP.edit().putString("work_id", work_id).commit();
        isWorkId = true;
        WorkOrder.DataEntity dataEntity = workOrder.getData().get(0);
        id = dataEntity.getId();
        realHandleWorkOrder = new ArrayList<>();
        workSP.edit().putString("procno", dataEntity.getProcno()).commit();
        et_work_order_id.setText(dataEntity.getRdsno());
        et_order_id.setText(dataEntity.getOrderno());
        et_cust_name.setText(dataEntity.getCustName());
        et_partId.setText(dataEntity.getPartid());
        et_procedure.setText(dataEntity.getProcName());
        et_product_name.setText(dataEntity.getProdName());
        et_should_num.setText(dataEntity.getReqnumb() + "");
        et_already_num.setText(dataEntity.getFinishnumb() + "");//已生产数
//        本工序的車頭數(最大)=上工序完成數*(本工序應產數/上工序良品數)
//
//        本次的車頭數=本工序的車頭數(最大)-已生產數
//
//        未生產餘數=應生產數-已生數-本次的車頭數

//        reqnumb	fNumb	finishnumb	allowNumb
//       150	   0.00	      0        	0	         100

        alreadyNum = Integer.valueOf(dataEntity.getFinishnumb());
        thisAllow = 0;//dataEntity.getAllowNumb() - alreadyNum;
        nofinishNum = dataEntity.getReqnumb() - alreadyNum;//- thisAllow;
        thisAllow = dataEntity.getAllowNumb() - alreadyNum;
        sheetNumb = Integer.parseInt(dataEntity.getSheetNumb());
        realHandleWorkOrder.add(dataEntity);
        et_no_finish_num.setText(nofinishNum + "");//未生产余数
        procno = dataEntity.getProcno();
//        isPrintVisviable(dataEntity.getIsPrint());


    }

    public void isPrintVisviable(int isPrint) {
        if (1 == isPrint) {
            rl9.setVisibility(View.VISIBLE);
            rl10.setVisibility(View.VISIBLE);
            rl11.setVisibility(View.VISIBLE);
            rl12.setVisibility(View.VISIBLE);
            rl13.setVisibility(View.VISIBLE);
        } else {
            rl9.setVisibility(View.GONE);
            rl10.setVisibility(View.GONE);
            rl11.setVisibility(View.GONE);
            rl12.setVisibility(View.GONE);
            rl13.setVisibility(View.GONE);
        }
    }

    String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        return date;
    }

    @Override
    public void queryWFail(String failMsg) {
        mProgressDialog.cancel();
        isWorkId = false;
        ToastUtil.showToast(getContext(), failMsg);
    }

    @Override
    public void findMSuccess(MachineInfo machineInfo) {
        mProgressDialog.cancel();
        workSP.edit().putString("machine_id", machine_id).commit();
        isMachineInfo = true;
        et_machine_id.setText("(" + machineInfo.getData().get(0).getName() + ")");
        et_machine_id.setFocusable(false);
        et_machine_id.setFocusableInTouchMode(false);
        barZbid = machineInfo.getData().get(0).getProddailyid();
        Log.d(TAG, "findMSuccess: " + isExist);
        if (!machineInfo.getData().get(0).getStarttime().equals("")
                && machineInfo.getData().get(0).getEndtime().equals("")) {

            isExist = true;
            clickControl(isExist);
            et_e_time.setText(getCurrentTime());
            et_s_time.setText(machineInfo.getData().get(0).getStarttime());
            long eTime = System.currentTimeMillis();
            workSP.edit().putLong("eTime", eTime).commit();
        } else {
            isExist = false;
//            isExist=true;
            clickControl(isExist);
            et_s_time.setText(getCurrentTime());
            long sTime = System.currentTimeMillis();
            workSP.edit().putLong("sTime", sTime).commit();
        }

    }

    private void clickControl(boolean isExist) {
        et_produce_num.setClickable(isExist);
        et_produce_num.setFocusable(isExist);
        et_produce_num.setEnabled(isExist);
        et_produce_num.setFocusableInTouchMode(isExist);
        et_people_group.setEnabled(isExist);
        et_people_group.setClickable(isExist);
        et_people_group.setFocusable(isExist);
        et_people_group.setFocusableInTouchMode(isExist);

        et_team_group.setEnabled(isExist);
        et_team_group.setClickable(isExist);
        et_team_group.setFocusable(isExist);
        et_team_group.setFocusableInTouchMode(isExist);

        clickSet(etPrintColor, isExist);
        clickSet(etPrintCode, isExist);
        clickSet(etPrintPrctType, isExist);
        clickSet(etDraftflowD, isExist);
        clickSet(etHalfStorage, isExist);
        clickSet(etChangeTime, isExist);
        clickSet(etWaitTime, isExist);
        clickSet(etDelayTime, isExist);
        clickSet(etRemark, isExist);

        if (isExist) {
            spPrintType.setAdapter(printTypeAdapter);
            spPrintPoNe.setAdapter(printPoNeAdapter);
        } else {
            spPrintType.setAdapter(emptyAdapter);
            spPrintPoNe.setAdapter(emptyAdapter);
        }
        add_item.setClickable(isExist);
        bt_w_delete.setEnabled(isExist);
        add_item.setVisibility((isExist ? View.VISIBLE : View.GONE));

    }

    public void clickSet(EditText editText, boolean isclik) {
        editText.setClickable(isclik);
        editText.setFocusable(isclik);
        editText.setEnabled(isclik);
        editText.setFocusableInTouchMode(isclik);
    }


    @Override
    public void findMFail(String failMsg) {

        mProgressDialog.cancel();
        isMachineInfo = false;
        ToastUtil.showToast(getContext(), failMsg);
    }

    @Override
    public void updateTSSuccess(UpdateInfo updateInfo) {

    }

    @Override
    public void updateTSFail(String fail) {

    }


    //班组人组查询结果
    @Override
    public void findWPSuccess(final PDistrubiton_JijianNumb pDistrubition) {
        if (null==pDistrubition.getData()){
            ToastUtil.showToast(getContext(),pDistrubition.getInfo());
            return;
        }
        pdistrubition = new ArrayList<>();
        for (PDistrubiton_JijianNumb.DataBeanX.DataBean pd : pDistrubition.getData().getData()) {
            pdistrubition.add(pd);
            Log.d(TAG, "keepTheData: ddd" + pd.getCode() + ":" + pd.getName());
        }

        mProgressDialog.cancel();
        adapter = new HZRBWorkAdapter(getContext());
        adapter.addContext(getContext());
        adapter.addItems(pdistrubition);
        itemRemoveRecycleView.setAdapter(adapter);
//计件数量点击事件
        adapter.setOnJiJianNumbClickListener(new HZRBWorkAdapter.OnJiJianNumbClickListener() {
            @Override
            public void onClick(final int postion) {
                final EditText inputServer = new EditText(getContext());
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("Server").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer)
                        .setNegativeButton("Cancel", null);
                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        pdistrubition.get(postion).setJijianNumb(stringToNumb(inputServer.getText().toString()));
                        adapter.notifyDataSetChanged();

                    }
                });
                builder.show();
            }
        });
        itemRemoveRecycleView.setOnItemClickListener(new ItemRemoveRecycleView.ItemOnListener() {
            @Override
            public void onItemDelete(int position) {

                adapter.removeItem(position);
                pdistrubition.remove(position);
                itemRemoveRecycleView.removeViewAt(position);

            }
        });

    }

    @Override
    public void findWPFail(String fail) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), fail);
    }

    @Override
    public void insertSPSuccess(UpdateInfo info) {
        mProgressDialog.cancel();
        emptyEt();
        et_inputer.setText(mySetting.getString("mCode", ""));
        et_machine_id.setText(machine_code);
        ToastUtil.showToast(getContext(), info.getInfo());
    }

    @Override
    public void insertSPFail(String fail) {

        mProgressDialog.cancel();

        ToastUtil.showToast(getContext(), fail);
    }

    @Override
    public void insertEPSuccess(UpdateInfo info) {
        mProgressDialog.cancel();
        emptyEt();
        machine_code="";
        et_inputer.setText(mySetting.getString("mCode", ""));
        ToastUtil.showToast(getContext(), info.getInfo());
    }

    @Override
    public void insertEPFail(String fail) {
        mProgressDialog.cancel();

        ToastUtil.showToast(getContext(), fail);
    }


    private void emptyEt() {
        workSP.edit().clear().commit();
        et_inputer.setText("");
        et_inputer.setFocusableInTouchMode(true);
        et_inputer.setFocusable(true);
        btn_inpter.setText(resources.getString(R.string.btn_ok_inputer));
        id = 0;
        et_work_order_id.setText("");
        et_work_order_id.setFocusableInTouchMode(true);
        et_work_order_id.setFocusable(true);
        et_s_time.setText("");
        et_e_time.setText("");
        et_machine_id.setText("");
        et_machine_id.setFocusableInTouchMode(true);
        et_machine_id.setFocusable(true);
        et_order_id.setText("");
        et_cust_name.setText("");
        et_partId.setText("");
        et_procedure.setText("");
        et_already_num.setText("");
        et_produce_num.setEnabled(false);
        et_produce_num.setText("");
        et_product_name.setText("");
        et_should_num.setText("");
        et_no_finish_num.setText("");
        et_people_group.setText("");
        et_team_group.setText("");
        setEditTextEmpty(etPrintColor);
        setEditTextEmpty(etPrintCode);
        setEditTextEmpty(etPrintPrctType);
        setEditTextEmpty(etDraftflowD);
        setEditTextEmpty(etHalfStorage);
        setEditTextEmpty(etChangeTime);
        setEditTextEmpty(etWaitTime);
        setEditTextEmpty(etDelayTime);
        setEditTextEmpty(etRemark);

        if (null != adapter && pdistrubition.size() > 0) {
//        if (null != adapter) {

            adapter.deleteItems(pdistrubition);
            adapter = null;
            pdistrubition = null;
        }

        cb_is_finish.setChecked(false);
        isInputer = false;
        isMachineInfo = false;
        isWorkId = false;
    }

    private void setEditTextEmpty(EditText editText) {

        editText.setEnabled(false);
        editText.setText("");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        workSP.edit().clear().commit();
        realHandleWorkOrder = null;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    public void text() {

    }
}
